package com.shop.user.mqHandler.listener;

import com.shop.ex.ShoppingException;
import com.shop.feignClient.GoodsClient;
import com.shop.po.R;
import com.shop.user.mapper.DiscountUserMapper;
import com.shop.user.mapper.OrderMapper;
import com.shop.user.po.OrderDetail;
import com.shop.user.po.Orders;
import com.shop.user.po.dto.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 'banxia'
 * @version 1.0
 * @description 用于接收死信交换机--->取消订单
 * @date 2023/2/28 13:55
 */
@Component
@Slf4j
public class OrderCanceListener {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private DiscountUserMapper discountUserMapper;

    @Autowired
    private GoodsClient goodsClient;

    //这里的默认策略是：执行失败自动再次执行---需要配置一定的策略！！
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "order.queue",durable = "true"),
            exchange = @Exchange(name = "order.direct",type = ExchangeTypes.DIRECT),
            key="orderCancel"
    ))
    public void listenerOrderCancel(String msg){
        log.debug("================================");
        log.debug("死信交换机接收到消息:{}",msg);
        log.debug("================================");
        if (StringUtils.isEmpty(msg)){
            log.error("接受到的消息为null");
            return;
        }
//        int i=1/0;//故意制造异常
        Long orderId=Long.parseLong(msg);
        //查看订单的详细情况。。
        OrderInfo orderInfo = orderMapper.getOrderInfo(orderId);
        //若已经支付，则跳过
        if(!orderInfo.getState().equals("0")){
            return;
        }
        //获取到分布式锁
//        redissonClient.getLock("orderCancel");
        //查看是否存在优惠券
        if (orderInfo.getDiscountId() != null) {
            //修改用户优惠券。。
            Long userId = orderInfo.getUserId();
            Long discountId = orderInfo.getDiscountId();
            discountUserMapper.cancelOrderDiscountRollBack(userId, discountId);
        }
        //更新订单表状态-->
        Orders orders = new Orders();
        orders.setId(orderId);
        orders.setState("2");//已删除
        //这里获取不到用户id（因为用户请求已经没了，本地线程也就获取不到）
        orders.setUpdateUser(orderInfo.getUserId());
        orderMapper.updateById(orders);

        //对商品库存进行回填--Feign调用
        List<OrderDetail> list = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : list) {
            Long goodsBaseId = orderDetail.getGoodsBaseId();
            Integer count = orderDetail.getCount();
            //对商品进行库存回填
            R r = goodsClient.goodsCountUpdate(goodsBaseId, (long) count);
            if (!r.getCode().equals(200)) {
                log.error("怎么解决。。。。。。。。。。。。？？？");
                log.error("这里更新出错了发送到管理员处理？？");
                ShoppingException.ThrowShoppingException("error");
            }
        }

    }

}
